package pers.lls.im.core.bootstrap.channel;

import com.google.gson.Gson;
import pers.lls.im.core.bootstrap.channel.cache.ChatCacheMap;
import pers.lls.im.core.bootstrap.handler.base.HandlerService;
import pers.lls.im.core.common.BeanFactoryDcp;
import pers.lls.im.core.common.bean.ChatMessage;
//import pers.lls.im.entity.GroupUser;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.util.List;


/**
 * @author lihuan
 * @version V1.0 创建时间：2019/8/02
 * Copyright 2019 by landray & STIC
 */
@Slf4j
public class HandlerServiceImpl implements HandlerService {

    @Override
    public boolean registry(Channel channel, ChatMessage chatMessage) {
        if (check(channel, chatMessage)) {
            Gson gson = new Gson();
            Channel other = ChatCacheMap.getByToken(chatMessage.getSender());
            //用记上线后，发送离线时未接收的消息
//            Map map = BeanFactoryDcp.messagePersistService.getHistoryMessage(chatMessage.getSender());
//            if ( map!= null && map.size() > 0) {
//                other.writeAndFlush(new TextWebSocketFrame(gson.toJson(gson.toJson(map))));
//            }
            //历史消息发送成功后，修改其状态

        }
        return true;
    }


    @Override
    public void sendToOne(Channel channel, ChatMessage chatMessage) {
        Gson gson = new Gson();
        String otherOne = chatMessage.getReceiver();
        //返回给自己
        channel.writeAndFlush(new TextWebSocketFrame(gson.toJson(chatMessage)));
        if (ChatCacheMap.hasToken(otherOne)) {
            //在线
            Channel other = ChatCacheMap.getByToken(otherOne);
            other.writeAndFlush(new TextWebSocketFrame(gson.toJson(chatMessage)));
        } else {
            //离线
            chatMessage.setStatus(1);
            BeanFactoryDcp.unReadMessageService.addUnRdMsg(chatMessage.getSender(),chatMessage.getReceiver(),"1");
            BeanFactoryDcp.dataAsynchronousTask.writeData(chatMessage);
            return;
            //持久化消息  状态离线 未发送成功
        }
        //聊天记录持久化
        //持久化消息
        chatMessage.setStatus(1);
        BeanFactoryDcp.dataAsynchronousTask.writeData(chatMessage);

    }

    @Override
    public void sendToGroup(Channel channel, ChatMessage chatMessage) {
        Gson gson = new Gson();
        String groupId = chatMessage.getGroupId();
        String sender = chatMessage.getSender();
//        List<GroupUser> array = BeanFactoryDcp.verifyService.getArrayByGroupId(groupId);
//        channel.writeAndFlush(new TextWebSocketFrame(gson.toJson(chatMessage)));
//        for (GroupUser item : array) {
//            if (!sender.equals(item.getUserId())) {
//                if (ChatCacheMap.hasToken(item.getUserId())) {
//                    Channel other = ChatCacheMap.getByToken(item.getUserId());
//                    other.writeAndFlush(new TextWebSocketFrame(gson.toJson(chatMessage)));
//                    //持久化消息记录
////                    chatMessage.setStatus(1);
////                    BeanFactoryDcp.dataAsynchronousTask.writeData(chatMessage);
//                } else {
//                    //存入消息  状态离线
//
//                    //持久化消息记录
////                    chatMessage.setStatus(0);
////                    BeanFactoryDcp.dataAsynchronousTask.writeData(chatMessage);
//                }
//            }
//        }
        chatMessage.setStatus(1);
        //消息状态未认未读
        BeanFactoryDcp.unReadMessageService.addUnRdMsg(chatMessage.getSender(),chatMessage.getReceiver(),"2");
        BeanFactoryDcp.dataAsynchronousTask.writeData(chatMessage);
    }

    @Override
    public void verify(Channel channel, ChatMessage chatMessage) {
        String token = chatMessage.getToken();
        if (BeanFactoryDcp.verifyService.verifyToken(token)) {
            //nothing
        } else {
            channel.writeAndFlush(new TextWebSocketFrame("用户校验出错！"));
            close(channel);
        }
    }

    @Override
    public void getUnreadMessage(Channel channel, ChatMessage chatMessage) {
        Gson gson = new Gson();
        String userId = chatMessage.getSender();
        chatMessage.setUnRdmsg(BeanFactoryDcp.unReadMessageService.getUnRdMsg(userId));
        channel.writeAndFlush(new TextWebSocketFrame(gson.toJson(chatMessage)));
    }

    @Override
    public boolean removeUnread(Channel channel, ChatMessage chatMessage) {
        String userId = chatMessage.getSender();
        String fromId = chatMessage.getReceiver();
        BeanFactoryDcp.unReadMessageService.removeUnRead(userId, fromId);
        return false;
    }


    private Boolean check(Channel channel, ChatMessage chatMessage) {
        String token = chatMessage.getToken();
        String userId = chatMessage.getSender();

        if (BeanFactoryDcp.verifyService.verifyToken(token)) {
            channel.writeAndFlush(new TextWebSocketFrame("用户注册成功！"));
            ChatCacheMap.saveWs(userId, channel);
            ChatCacheMap.saveAd(channel.remoteAddress().toString(), userId);
            return true;
        }
        channel.writeAndFlush(new TextWebSocketFrame("用户注册失败！"));
        close(channel);
        return false;
    }

    @Override
    public void close(Channel channel) {
        String token = ChatCacheMap.getByAddress(channel.remoteAddress().toString());
        ChatCacheMap.deleteAd(channel.remoteAddress().toString());
        ChatCacheMap.deleteWs(token);
        channel.close();
    }

}
